package com.diy.task.sys.service.impl;

import cn.hutool.core.io.FileUtil;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.diy.task.common.base.BaseResult;
import com.diy.task.common.exception.BizExceptionEnum;
import com.diy.task.common.exception.BussinessException;
import com.diy.task.common.importbus.authuser.ImportAuthUser;
import com.diy.task.common.importbus.authuser.ImportAuthUserExcelListener;
import com.diy.task.common.exportbus.ExportUtils;
import com.diy.task.common.utils.Constant;
import com.diy.task.sys.entity.AuthUser;
import com.diy.task.sys.mapper.AuthUserMapper;
import com.diy.task.sys.service.IAuthUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author hxm
 * @since 2019-03-05
 */
@Service
public class AuthUserServiceImpl extends ServiceImpl<AuthUserMapper, AuthUser> implements IAuthUserService {

    private static final Logger LOGGER = LoggerFactory.getLogger(AuthUserServiceImpl.class);

    @Autowired
    private AuthUserMapper authUserMapper;

    @Autowired
    private RedisTemplate<String, Serializable> redisTemplate;




    /**
     * 登录
     * @param request
     * @param userName
     * @param password
     * @return
     */
    @Override
    public BaseResult login(HttpServletRequest request, String userName, String password) {
        LOGGER.info("login方法已执行,参数用户名：{},密码：{}",userName,password);
        AuthUser authUser = new AuthUser();
        authUser.setUserName(userName);
        authUser.setPassword(password);
        authUser.setDeleted(Constant.ZERO.getCode());
        AuthUser user = authUserMapper.selectOne(new Wrapper<AuthUser>() {
            @Override
            public AuthUser getEntity() {
                return authUser;
            }

            @Override
            public String getSqlSegment() {
                return null;
            }
        });
        if (ObjectUtils.isEmpty(user)){
            LOGGER.error("用户名或密码不对！");
            return BaseResult.error("用户名或密码不对！");
        }
        HttpSession session = request.getSession();
        redisTemplate.opsForValue().set(session.getId(),user,24, TimeUnit.HOURS);
        Map map = new HashMap(3);
        map.put("id",user.getId());
        map.put("status","ok");
        map.put("currentAuthority",user.getUserType());
        map.put("type","account");
        return BaseResult.ok("登录成功！",map);
    }



    /**
     * 导出未提交的学员名单
     */
    @Override
    public void export(HttpServletResponse httpServletResponse,String fileName) {
        LOGGER.info("export方法已执行");
        List<String> unSubmittedNameList = authUserMapper.getUnSubmittedName();
        try {
            ExportUtils.exportUnSubmittedName(httpServletResponse,fileName,unSubmittedNameList);
        }catch (Exception e){
            LOGGER.error("导出未提交的学员名单数据出错",e.getMessage(),e);
        }
    }

    /**
     * 导入学生的名单
     */
    @Override
    public void importUserInfo() {
        BufferedInputStream inputStream = FileUtil.getInputStream("d://学生名单表.xlsx");
        try{
            ImportAuthUserExcelListener importAuthUserExcelListener = new ImportAuthUserExcelListener();
            ExcelReader excelReader = new ExcelReader(inputStream, ExcelTypeEnum.XLSX, null, importAuthUserExcelListener);
            excelReader.read(new Sheet(0,2, ImportAuthUser.class));
        }catch (Exception e){
            LOGGER.error("导入学生名单表表格数据出错",e.getMessage(),e);
        }finally {
            try {
                if(inputStream != null){
                    inputStream.close();
                }
            } catch (IOException e) {
                throw new BussinessException(BizExceptionEnum.IMPORT_ERROR);
            }
        }
    }
}
